﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace SharePointUtilitiesForDevelopers.Mapper
{
    /// <summary>
    /// A mapper that maps the xml web service response to a <see cref="SharePointWeb"/>.
    /// </summary>
    public class SharePointWebMapper : IMapper<XElement, SharePointWeb>
    {

        /// <summary>
        /// Maps the source type to the target type.
        /// </summary>
        /// <param name="from">The object to map from.</param>
        /// <returns>The mapped object.</returns>
        public SharePointWeb Map(XElement from)
        {
            return MapList(from).SingleOrDefault();
        }
        
        /// <summary>
        /// Maps the source type to a list of the target type.
        /// </summary>
        /// <param name="from">From.</param>
        /// <returns></returns>
        public IEnumerable<SharePointWeb> MapList(XElement from)
        {
            try
            {
                var webs = SharePointMapper.MapResponseToList<SharePointWeb>(
                    MapInternal,
                    element => string.Compare(element.Name.LocalName, "Web", StringComparison.InvariantCultureIgnoreCase) == 0,
                    from);

                return webs;
            }
            catch (Exception ex)
            {
                throw new SharePointMapperException<XElement, IEnumerable<SharePointWeb>>(ex);
            }
        }

        /// <summary>
        /// Maps the element to a domain object.
        /// </summary>
        /// <param name="element">The element to map from.</param>
        /// <returns>The mapped object.</returns>
        private static SharePointWeb MapInternal(XElement element)
        {
            return new SharePointWeb
                       {
                           Title = SharePointXml.GetAttributeAsString(element, "Title"),
                           Url = SharePointXml.GetAttributeAsString(element, "Url"),
                           Definition = element
                       };
        }
    }
}